//package com.pig4cloud.pigx.user.schedule;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.util.StrUtil;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.pig4cloud.pigx.common.customize.enums.CommonDictEnum;
//import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
//import com.pig4cloud.pigx.user.constant.WalletConstant;
//import com.pig4cloud.pigx.user.entity.Currency;
//import com.pig4cloud.pigx.user.entity.CurrentBlock;
//import com.pig4cloud.pigx.user.entity.RechargeRecord;
//import com.pig4cloud.pigx.user.entity.UserAddress;
//import com.pig4cloud.pigx.user.enums.RechargeRecordEnum;
//import com.pig4cloud.pigx.user.enums.UserEnums;
//import com.pig4cloud.pigx.user.service.CurrencyService;
//import com.pig4cloud.pigx.user.service.CurrentBlockService;
//import com.pig4cloud.pigx.user.service.RechargeRecordService;
//import com.pig4cloud.pigx.user.service.UserAddressService;
//import io.reactivex.Flowable;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import okhttp3.OkHttpClient;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.security.core.parameters.P;
//import org.springframework.stereotype.Component;
//import org.web3j.abi.EventEncoder;
//import org.web3j.abi.TypeReference;
//import org.web3j.abi.datatypes.Address;
//import org.web3j.abi.datatypes.Event;
//import org.web3j.abi.datatypes.generated.Uint256;
//import org.web3j.protocol.Web3j;
//import org.web3j.protocol.core.DefaultBlockParameter;
//import org.web3j.protocol.core.methods.request.EthFilter;
//import org.web3j.protocol.core.methods.response.EthBlock;
//import org.web3j.protocol.core.methods.response.EthBlockNumber;
//import org.web3j.protocol.core.methods.response.EthLog;
//import org.web3j.protocol.http.HttpService;
//import org.web3j.utils.Convert;
//
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.math.BigInteger;
//import java.math.RoundingMode;
//import java.time.LocalDateTime;
//import java.util.Arrays;
//import java.util.List;
//import java.util.stream.Collectors;
//
///**
// * bsc充值
// *
// */
//@Slf4j
//@Component
//@EnableScheduling
//@AllArgsConstructor
//public class BscRecharge {
//
//	private final CurrentBlockService currentBlockService;
//
//	private final CurrencyService currencyService;
//
//	private final UserAddressService addressService;
//
//	private final RechargeRecordService rechargeRecordService;
//
//	private final IdWorker idWorker;
//
//	@Scheduled(fixedDelay = 1000)
//	public void task() {
//		try {
//			// 获取UNT 币种
//			Currency currencyServiceOne = currencyService.getOne(new LambdaQueryWrapper<Currency>()
//					.eq(Currency::getPublicChain, UserEnums.Chain.BSC.getValue())
//					.eq(Currency::getName, WalletConstant.USDT)
//					.eq(Currency::getState, CommonDictEnum.Status.NORMAL.getValue())
//			);
//			Web3j web3j = Web3j.build(new HttpService(currencyServiceOne.getNodeAddress()));
//			// TODO 争夺分布式事务锁
//			// 连接USC-API
//			// 获取区块
//			CurrentBlock currentBlock = currentBlockService.getOne(new LambdaQueryWrapper<CurrentBlock>()
//					.eq(CurrentBlock::getPublicChain, UserEnums.Chain.BSC.getValue())
//			);
//			// 初始化区块
//			if (currentBlock == null) {
//				org.web3j.protocol.core.Request<?, EthBlockNumber> ethBlockNumberRequest = web3j.ethBlockNumber();
//				EthBlockNumber send;
//				try {
//					send = ethBlockNumberRequest.send();
//				} catch (IOException e) {
//					throw new RuntimeException(e);
//				}
//				BigInteger blockNumber = send.getBlockNumber();
//				currentBlock = new CurrentBlock();
//				currentBlock.setPublicChain(UserEnums.Chain.BSC.getValue());
//				currentBlock.setBlockNumber(String.valueOf(blockNumber));
//				currentBlockService.save(currentBlock);
//			}
//
//			final String[] blockNumber = {currentBlock.getBlockNumber()};
//
//			Flowable<EthBlock> ethBlockFlowable = web3j.replayPastAndFutureBlocksFlowable(
//					DefaultBlockParameter.valueOf(BigInteger.valueOf(Long.parseLong(blockNumber[0]))),
//					false);
//
//			CurrentBlock currentBlockUpdate = new CurrentBlock();
//			currentBlockUpdate.setId(currentBlock.getId());
//
//			ethBlockFlowable.blockingSubscribe(ethBlock -> {
//				EthFilter filter = new EthFilter(ethBlock.getBlock().getHash(), currencyServiceOne.getSmartContractAddress());
//				Event event = new Event("Transfer",
//						Arrays.<TypeReference<?>>asList(
//								new TypeReference<Address>(true) {
//								},
//								new TypeReference<Address>(true) {
//								},
//								new TypeReference<Uint256>(true) {
//								}));
//				filter.addSingleTopic(EventEncoder.encode(event));
//				org.web3j.protocol.core.Request<?, EthLog> ethLogRequest = web3j.ethGetLogs(filter);
//				EthLog send = ethLogRequest.send();
//				List<EthLog.LogResult> logs = send.getLogs();
//				if (CollUtil.isNotEmpty(logs)) {
//					logs.forEach(logResult -> {
//						EthLog.LogObject logObject = (EthLog.LogObject) logResult.get();
//						// log.info("eth区块高度：{},交易记录：{}", ethBlock.getBlock().getNumber(), JSONUtil.parseObj(logObject));
//						String toReplace = StrUtil.replace(logObject.getTopics().get(2), 2, 26, "");
//						// 获取用户钱包地址
//						List<UserAddress> list = addressService.list(new QueryWrapper<UserAddress>() {{
//							eq("chain", UserEnums.Chain.BSC.getValue());
//						}});
//						if (CollUtil.isNotEmpty(list)) {
//							List<String> addressList = list.stream().map(UserAddress::getAddress).collect(Collectors.toList());
//							boolean contains = CollUtil.contains(addressList, toReplace);
//							if (contains) {
//								log.info("BSC地址匹配成功,交易哈希：{}", logObject.getTransactionHash());
//
//								RechargeRecord recordServiceOne = rechargeRecordService.getOne(new LambdaQueryWrapper<RechargeRecord>()
//										.eq(RechargeRecord::getTransactionHash, logObject.getTransactionHash())
//								);
//
//								if (recordServiceOne != null) {
//									log.error("BSC存在相同交易哈希：{}", logObject.getTransactionHash());
//									return;
//								}
//
//								// 获取充值用户
//								List<UserAddress> collect = list.stream().filter(address -> StrUtil.equals(address.getAddress(), toReplace)).collect(Collectors.toList());
//								if (collect.size() < 1) {
//									return;
//								}
//								UserAddress userAddress = collect.get(0);
//								// 获取充值数量
//								String valueStr = new BigInteger(logObject.getData().substring(2), 16).toString();
//								BigDecimal balance = Convert.fromWei(new BigDecimal(valueStr), Convert.Unit.ETHER).setScale(currencyServiceOne.getAccuracy(), RoundingMode.DOWN);
//								// 充值记录
//								RechargeRecord rechargeRecord = new RechargeRecord();
//								rechargeRecord.setId(idWorker.nextId());
//								// 公链
//								rechargeRecord.setPublicChain(UserEnums.Chain.BSC.getValue());
//								// 账户地址id
//								rechargeRecord.setAddressId(userAddress.getId());
//								// 用户id
//								rechargeRecord.setUserId(userAddress.getUserId());
//								// 区块
//								rechargeRecord.setBlockNumber(String.valueOf(ethBlock.getBlock().getNumber()));
//								// 充值数量
//								rechargeRecord.setQuantity(balance);
//								// 到账地址
//								rechargeRecord.setArrivalAddress(toReplace);
//								// 来源地址
//								String fromReplace = StrUtil.replace(logObject.getTopics().get(1), 2, 26, "");
//								rechargeRecord.setSourceAddress(fromReplace);
//								// 区块确认数
//								rechargeRecord.setBlockConfirmationNumber("0");
//								// 交易哈希
//								rechargeRecord.setTransactionHash(logObject.getTransactionHash());
//								// 充值区块确认数
//								rechargeRecord.setBlockConfirmationRechargeNumber(currencyServiceOne.getConfirmationBlockRechargeNumber());
//								// 最小充值数
//								rechargeRecord.setMinimumRechargeNumber(currencyServiceOne.getMinimumRechargeAmount());
//								// 手续费
//								rechargeRecord.setServiceCharge(currencyServiceOne.getServiceCharge());
//								// 币种
//								rechargeRecord.setCurrency(currencyServiceOne.getName());
//								// 状态
//								rechargeRecord.setState(RechargeRecordEnum.Status.RECHARGING.getValue());
//								// 充值类型
//								rechargeRecord.setType(RechargeRecordEnum.Type.CHAIN_RECHARGE.getValue());
//								rechargeRecordService.save(rechargeRecord);
//							}
//						}
//					});
//				}
//				currentBlockUpdate.setBlockNumber(String.valueOf(ethBlock.getBlock().getNumber()));
//				currentBlockService.updateById(currentBlockUpdate);
//			}, throwable -> {
//				throw new RuntimeException(throwable.getMessage());
//			});
//		} catch (Exception e) {
//			log.error("bsc充值定时任务 inTime[" + LocalDateTime.now() + "] error + " + e);
//		}
//		log.error("bsc充值定时任务 inTime[" + LocalDateTime.now() + "] success");
//	}
//
//}
